package com.fingard.dsp.bank.directbank.fuiou01;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.directbank.fngrd01.FnGrd01Header;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.net.SftpPortClient;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import java.io.File;
import java.util.ArrayList;
/**
 * 富有电子回单
 *
 * @author Latte
 * @version 1.0
 * @date created in 2019/5/27
 * @modify 2019/5/27
 */
public class FUIOU01Receipt extends FUIOU01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {

        return qryReceiptXml(p_reqReceipt);

    }
    private RetAtsReceipt qryReceiptXml(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        FUIOU01Header bankHeader = new FUIOU01Header();
        FtpPortClient ftpPtClient = null;
        String tmpRespCode = "";
        String tmpRespInfo = "";
        String orderNo="";
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqReceipt.actNum, "receipt");
            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            if (actItem != null&&ftpSet != null) {
                ftpPtClient = new FtpPortClient(ftpSet);
                DataFileHelper dFileHelper = new DataFileHelper(this);
                while(tmpIntFrom<=tmpIntTo){
                    Date intFromStep = tmpCalendarFrom.getTime();
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                    String dataFilePath = dFileHelper.getBankReceiptDataFile(intFromStep, p_reqReceipt.actNum);
                    File dataFile = new File(dataFilePath);
                    if (dataFile.exists()) {
                        WriteBankLogLn(Format.Date8Format.format(intFromStep) + "的回单已执行过下载，如需重新获取，请删除文件" + dataFilePath);
                        retAts.respCode = "0";
                        retAts.respInfo = Format.Date8Format.format(intFromStep) + "的回单已执行过下载";
                        continue;
                    }
                    //第一步
                    WriteBankLogLn("查询" + tmpIntFrom + "流水号");
                    //1、查询当前时间的明细流水，匹配流水号，账号，只下载有明细流水的电子回单
                    String receiptString=selectReceipt(p_reqReceipt.actNum,Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    String[] receiptArray=receiptString.replaceAll(" ","").split("\\|");//查询到明细的流水串
                    //String[] receiptArray={"29061303172135"};
                    for(int i=0;i<receiptArray.length;i++){
                        XmlTextWriter xmlWriter = new XmlTextWriter();
                        xmlWriter.autoFormat = false;
                        orderNo=receiptArray[i];
                        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
                        xmlWriter.writeStartElement("qryReceipt");
                        xmlWriter.writeElementString("mchntCd", actItem.merchantId);
                        String txnDate=Format.Date8Format.format(intFromStep);
                        xmlWriter.writeElementString("txnDate", txnDate);
                        xmlWriter.writeElementString("orderNo", orderNo);
                        String reqStr = actItem.merchantId + "|" + txnDate + "|" +orderNo;
                        String[] transTypes = reqStr.split("\\|");
                        String sign= hex(transTypes,actItem.saltKey);
                        xmlWriter.writeElementString("signature", sign);
                        xmlWriter.writeEndElement();
                        String[] tmpStrRet = sendToBank("Receipt",xmlWriter.toXmlString(),true);
                        if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmpRetCode = tmpBkReader.getFirstText("/qryReceipt/respCode");
                                // tmpRetCode="000000";
                                if ("000000".equals(tmpRetCode)) {
                                    //下载成功之后，保存回单数据文件
                                    boolean saveCacheData = true;
                                    retAts.respCode = "000000";
                                    retAts.respInfo = tmpBkReader.getFirstText("/qryReceipt/respDesc");
                                    //String tmpOrderNo=tmpBkReader.getFirstText("/qryReceipt/orderNo");
                                    //第二步
                                    WriteBankLogLn("开始执行" + txnDate + "的回单文件下载");
                                    String downFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + txnDate+ "/" + txnDate + "_"+orderNo+".pdf";

                                    String tmpLocalSavePath = createTempFileDirectory();
                                    String localSavePath = tmpLocalSavePath+File.separator + txnDate + "_"+orderNo+".pdf";
                                    WriteBankLogLn("开始下载服务器文件- [" + downFilePath + "],至本地- [" + localSavePath + "].");
                                    boolean isDownFileSucc = false;
                                    FtpReceiver tmpReceiver=null;
                                    if ("sftp".equals(ftpSet.ftpType.toLowerCase())){
                                        WriteBankLogLn("SFTP下载地址: [" + ftpSet.serverIP + ":" + ftpSet.port + "].");
                                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                                        tmpReceiver = sftpPortClient.downloadFile("",downFilePath, localSavePath);
                                    }else{
                                        tmpReceiver = ftpPtClient.downloadFile(downFilePath, localSavePath);
                                        WriteBankLogLn("FTP下载地址: [" + ftpSet.serverIP + ":" + ftpSet.port + "].");
                                    }
                                    WriteBankLogLn(ftpPtClient.sbLog);
                                    if (tmpReceiver.isCompleted) {
                                        WriteBankLogLn("文件下载已完成");
                                        File depressDir = new File(tmpLocalSavePath);
                                        if (depressDir.exists()) {
                                            File[] deFiles = depressDir.listFiles();
                                            if (deFiles != null && deFiles.length > 0) {
                                                isDownFileSucc = true;
                                            } else {
                                                tmpReceiver.connMsg += "文件夹" + localSavePath + "下为空";
                                            }
                                        } else {
                                            tmpReceiver.connMsg += "文件夹" + localSavePath + "不存在";
                                        }
                                    } else {
                                        WriteBankLogLn(tmpReceiver.connMsg);
                                        retAts.respInfo = tmpReceiver.connMsg;
                                    }
                                    if (isDownFileSucc) {
                                        File receiptDir = new File(tmpLocalSavePath);
                                        if (receiptDir.exists()) {
                                            ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                                            int tmpFileCount = 0;
                                            File[] receiptFiles = receiptDir.listFiles();
                                            for (File receiptFile : receiptFiles) {
                                                String eachName = receiptFile.getName();
                                                if (eachName.toLowerCase().endsWith(".pdf") && eachName.contains(orderNo)) {
                                                    ReceiptMapping eachRcptMp = new ReceiptMapping();
                                                    eachRcptMp.setBusDate(intFromStep);
                                                    eachRcptMp.ownAct = p_reqReceipt.actNum;
                                                    eachRcptMp.keyName = "receiptNo";
                                                    eachRcptMp.srcFile = StringHelper.getFileName(localSavePath);
                                                    eachRcptMp.askNumber=orderNo;
                                                    eachRcptMp.receiptNo=orderNo;
                                                    eachRcptMp.bank="9028";
                                                    eachRcptMp.amount = new BigDecimal(0);
                                                    HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, localSavePath);
                                                    WriteBankLogLn(saveResp.sbMsg);
                                                    if (saveResp.isCompleted) {
                                                        tmpFileCount++;
                                                        //listToDelete.add(localReceiptPath);
                                                        File toDel = new File(localSavePath);
                                                        WriteBankLogLn("删除文件" + toDel.getName());
                                                        toDel.delete();
                                                        //FileHelper.writeFile(dataFile, "文件" + receiptRelativePath + "推送成功!", getCharset());
                                                    } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                                        WriteBankLogLn("连接服务器失败，终止本次推送");
                                                        tmpRespCode = "-1";
                                                        tmpRespInfo = "连接服务器失败，终止本次推送";
                                                        break;
                                                    } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                                        WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                                        tmpRespCode = "-1";
                                                        tmpRespInfo = ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送";
                                                        break;
                                                    }
                                                } else if (eachName.toLowerCase().endsWith(".pdf")) {
                                                    receiptFile.delete(); // 删除pdf
                                                }
                                            }
                                            if(tmpRespCode == "-1"){
                                                break;
                                            }
                                            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
                                            for (File receiptFile : receiptFiles) {
                                                if (receiptFile.isFile()) {
                                                    receiptFile.delete(); // 删除文件
                                                }
                                                if (receiptFile.isDirectory()) {
                                                    receiptFile.delete(); // 删除账号目录
                                                }
                                            }
                                            if (receiptDir.exists()) {
                                                receiptDir.delete(); // 删除日期目录
                                            }
                                            retAts.respCode = tmpRespCode;
                                            retAts.respInfo = tmpRespInfo;
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "不存在回单目录:" + receiptDir.getName();
                                            break;
                                        }
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "下载文件失败：";
                                        if (tmpReceiver != null) {
                                            retAts.respInfo += tmpReceiver.connState + "-" + tmpReceiver.connMsg;
                                        }
                                        break;
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = tmpBkReader.getFirstText("/qryReceipt/respDesc");
                                    break;
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpSbMsg.toString();
                                break;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpStrRet[0] + tmpStrRet[1];
                            break;
                        }
                    }
                    if(retAts.respCode=="-1"){
                        break;
                    }
                }

            } else{
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_reqReceipt.actNum + "]配置信息!";
                WriteBankLogLn(retAts.respInfo);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }
}
